<?php
namespace Admin\Controller;
use Think\Controller;

class PassageController extends Controller {
	public function index(){
		$controller = I( 'get._c' );
		$action     = I( 'get._a' );
		//数据接口，转发到相应的action
		if( $action )
		{
			$controller = $controller ? $controller : CONTROLLER_NAME;
			R($controller."/".$action);
			return true;
		}
		
		$this->display();
	}
	
	public function passagedata(){
		$ret = array();
		$ret['status'] = 200;
		$ret['msg'] = "ok";
		$ret['content'] = array();
		
		try{
			$offset = I("iDisplayStart",0,"intval");
		
			$size = I("iDisplayLength",10,"intval");
			//             $offset = ($page - 1) * $size;
		
			$where = array();
			$keyword = I('sSearch');
			if( $keyword ) {
				$where['title']  = array('like','%'.$keyword.'%');
// 				$where['code']  = array('like','%'.$keyword.'%');
// 				$where['code2']  = array('like','%'.$keyword.'%');
// 				$where['_logic'] = 'or';
			}
			
			$passage = D("Passage");
			$data = $passage->where( $where )->limit("{$offset},{$size}")->order("id desc")->select();
			
			header('sql : '.$passage->getLastSql() );
			
			foreach ($data as $k=>$v){
				
				$data[$k]['options'] = '<a target="_self" href="#'.U("passage/add", "id=".$v['id'] ).'" class="charts-comments" title="编辑">编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target="_target" href="http://'.C('MAIN_DOMAIN')."/passage/read/id/".$v['id'].'" class="charts-comments" title="查看">查看</a>';
			}
			$total = $passage->where( $where )->count();
			
			$rs1 = array();
			$rs1['data'] = $data?$data:array();
			$ret['iTotalDisplayRecords'] = $total?$total:0;
			$ret['iTotalRecords'] = $total?$total:0;
			
			$ret['content'] = $rs1;
		}catch(\Exception $e){
			$ret['status'] = $e->getCode();
			$ret['msg'] = $e->getMessage();
		}
		$this->ajaxReturn($ret);
	}
	
	public function add(){
		$id = I("id",0,"intval");
		if( $id ){
			$passage = D("Passage");
			$data = $passage->where( "id=".$id )->find();
			$data['content'] = ($data['content']);
// 			$data['img'] = unserialize($data['img']);
			$this->assign("data",$data);
		}
		
		if( IS_POST ){
			
			$ret = array();
			$ret['status'] = 200;
			$ret['msg'] = "ok";
			$ret['data'] = array();
			 
			try{
				$id = I('id',0,'intval');
				
				$data = array();
				$data['title'] = I('title');
				$data['desc'] = I('desc');
				$data['content'] = I('content','','');
				$data['score'] = I('score',0,'intval');
				$data['readnum'] = I('readnum',0,'intval');
				$data['zannum'] = I('zannum',0,'intval');
				
				$passage = D("Passage");
				
				if( $id ){
					$where = array();
					$where['id'] = $id;
					
					$passage->where($where)->save($data);	
				}else{
					$passage->add( $data );
				}
			}catch(\Exception $e){
    			$ret['status'] = $e->getCode();
    			$ret['msg'] = $e->getMessage();
    		}
    		$this->ajaxReturn($ret);
		}else{
			$this->display();
		}
	}
}